import httpx
from typing import Dict, List, Any, Optional
from ..core.config import settings, NovelProject
import logging

logger = logging.getLogger(__name__)


class AIConversationService:
    """AI对话服务 - DeepSeek集成"""
    
    def __init__(self):
        self.api_key = settings.DEEPSEEK_API_KEY
        self.model = settings.DEEPSEEK_MODEL
        self.api_host = settings.DEEPSEEK_API_HOST
        self.max_tokens = settings.DEEPSEEK_MAX_TOKENS
        self.temperature = settings.DEEPSEEK_TEMPERATURE
        
        # 角色人设模板
        self.character_personalities = {
            NovelProject.DOULUO_DALU: {
                "唐三": {
                    "personality": "机智冷静，重情重义，有着强烈的正义感。作为唐门弟子，精通各种暗器和毒术。",
                    "background": "唐门外门弟子，后来成为史莱克七怪之一，拥有蓝银草和昊天锤双武魂。",
                    "speech_style": "语气谦和但坚定，善于分析，经常提及暗器和毒术知识。"
                },
                "小舞": {
                    "personality": "活泼开朗，天真烂漫，对唐三有着深深的爱意。实际身份是十万年魂兽。",
                    "background": "史莱克七怪之一，十万年柔骨兔化形，拥有强大的魂兽血脉。",
                    "speech_style": "语气活泼可爱，经常叫唐三'哥'，喜欢撒娇。"
                }
            },
            NovelProject.DOUPO_CANGQIONG: {
                "萧炎": {
                    "personality": "坚韧不拔，永不言败，为了复仇和保护重要的人可以付出一切。",
                    "background": "萧家三少爷，曾经是天才后来沦为废物，在药老师父帮助下重新崛起。",
                    "speech_style": "语气坚定自信，经常提及斗气和炼药，有时会展现霸气。"
                },
                "薰儿": {
                    "personality": "温柔体贴，聪明睿智，对萧炎有着深深的感情，身份神秘高贵。",
                    "background": "古族小姐，实力强大，从小与萧炎青梅竹马。",
                    "speech_style": "语气温和优雅，称呼萧炎为'萧炎哥哥'，说话文雅有礼。"
                }
            },
            NovelProject.CHANGAN_TWELVE: {
                "李必": {
                    "personality": "聪明机敏，忠君爱国，有着敏锐的洞察力和正义感。",
                    "background": "靖安司司丞，负责长安城的安全防务，深受皇帝信任。",
                    "speech_style": "语气严谨理性，经常分析案情，用词文雅，体现唐朝官员风范。"
                },
                "张小敬": {
                    "personality": "经验丰富，手段老辣，为了长安百姓可以不择手段。",
                    "background": "前不良帅，现任靖安司重要成员，熟悉长安城的每一个角落。",
                    "speech_style": "语气直接务实，经常用江湖俚语，体现底层百姓的智慧。"
                }
            }
        }
    
    def get_character_prompt(
        self, 
        character_name: str, 
        novel_project: NovelProject
    ) -> str:
        """获取角色人设提示词"""
        project_characters = self.character_personalities.get(
            novel_project, {}
        )
        character_info = project_characters.get(character_name)
        
        if not character_info:
            # 通用角色设定
            return f"""你是来自{novel_project}的角色{character_name}。
请保持角色的一致性，用符合角色身份的语言风格与用户对话。
保持友好、有趣的对话氛围。"""
        
        return f"""你是{novel_project}中的{character_name}。

角色设定：
- 性格特点：{character_info['personality']}
- 背景信息：{character_info['background']}
- 说话风格：{character_info['speech_style']}

请严格按照这个角色设定与用户对话，保持角色的一致性和真实感。
不要破坏角色设定，始终以{character_name}的身份回应。"""

    async def chat_with_character(
        self,
        character_name: str,
        novel_project: NovelProject,
        user_message: str,
        conversation_history: Optional[List[Dict[str, str]]] = None
    ) -> Dict[str, Any]:
        """与指定角色进行对话"""
        try:
            # 构建消息历史
            messages = [
                {
                    "role": "system",
                    "content": self.get_character_prompt(
                        character_name, novel_project
                    )
                }
            ]
            
            # 添加对话历史（最近10条）
            if conversation_history:
                for msg in conversation_history[-10:]:
                    sender_type = msg["sender_type"]
                    role = "user" if sender_type == "user" else "assistant"
                    messages.append({
                        "role": role,
                        "content": msg["content"]
                    })
            
            # 添加当前用户消息
            messages.append({
                "role": "user",
                "content": user_message
            })
            
            # 调用DeepSeek API
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.api_host}/chat/completions",
                    headers={
                        "Authorization": f"Bearer {self.api_key}",
                        "Content-Type": "application/json"
                    },
                    json={
                        "model": self.model,
                        "messages": messages,
                        "max_tokens": self.max_tokens,
                        "temperature": self.temperature,
                        "stream": False
                    },
                    timeout=30.0
                )
                
                if response.status_code != 200:
                    error_msg = (
                        f"DeepSeek API error: {response.status_code} - "
                        f"{response.text}"
                    )
                    logger.error(error_msg)
                    return {
                        "success": False,
                        "error": f"API调用失败: {response.status_code}",
                        "content": "抱歉，我现在无法回应，请稍后再试。"
                    }
                
                result = response.json()
                content = result["choices"][0]["message"]["content"]
                
                return {
                    "success": True,
                    "content": content.strip(),
                    "usage": result.get("usage", {}),
                    "model": self.model
                }
                
        except httpx.TimeoutException:
            logger.error("DeepSeek API timeout")
            return {
                "success": False,
                "error": "请求超时",
                "content": "抱歉，响应时间过长，请稍后再试。"
            }
        except Exception as e:
            logger.error(f"AI conversation error: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "content": "抱歉，出现了一些问题，请稍后再试。"
            }

    def get_welcome_message(
        self, 
        character_name: str, 
        novel_project: NovelProject
    ) -> str:
        """获取角色欢迎消息"""
        if novel_project == NovelProject.DOULUO_DALU:
            if character_name == "唐三":
                return "你好，我是唐三。很高兴认识你！有什么想了解的吗？"
            elif character_name == "小舞":
                return "嗨～我是小舞！好开心又遇到新朋友了呢！"
        elif novel_project == NovelProject.DOUPO_CANGQIONG:
            if character_name == "萧炎":
                return "我是萧炎，很荣幸与你相遇。有什么想聊的吗？"
            elif character_name == "薰儿":
                return "你好呀，我是薰儿。很高兴能和你交流～"
        elif novel_project == NovelProject.CHANGAN_TWELVE:
            if character_name == "李必":
                return "在下李必，靖安司司丞。阁下有何要事相询？"
            elif character_name == "张小敬":
                return "我是张小敬，长安城里的事儿，没有我不知道的。"
        
        return f"你好，我是{character_name}，很高兴认识你！"


# 创建全局AI服务实例
ai_service = AIConversationService() 